package ai.esc.speedy.common.context;

import ai.esc.speedy.admin.user.infrastructure.jwt.JwtUserInfo;
import ai.esc.speedy.common.constant.CommonConstants;

import java.util.HashMap;
import java.util.Map;

/**
 * @author SAGE
 * @version v1 2019/5/27 23:00
 */
public class BaseContextHandler {

    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(16);
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(16);
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void setPerson(JwtUserInfo person) {
        set(CommonConstants.CONTEXT_KEY_PERSON_OBJECT, person);
    }

    public static JwtUserInfo getPerson() {
        return (JwtUserInfo) get(CommonConstants.CONTEXT_KEY_PERSON_OBJECT);
    }

    public static Object getLoggedUser() {
        return get(CommonConstants.CONTEXT_KEY_USER_OBJECT);
    }

    public static String getUserID() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_ID);
        return returnObjectValue(value);
    }

    public static String getUsername() {
        Object value = get(CommonConstants.CONTEXT_KEY_USERNAME);
        return returnObjectValue(value);
    }


    public static String getName() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_NAME);
        return getObjectValue(value);
    }

    public static String getToken() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_TOKEN);
        return getObjectValue(value);
    }

    public static void setToken(String token) {
        set(CommonConstants.CONTEXT_KEY_USER_TOKEN, token);
    }

    public static void setName(String name) {
        set(CommonConstants.CONTEXT_KEY_USER_NAME, name);
    }

    public static void setLoggedUser(Object sysOrgPerson) {
        set(CommonConstants.CONTEXT_KEY_USER_OBJECT, sysOrgPerson);
    }

    public static void setUserID(String userID) {
        set(CommonConstants.CONTEXT_KEY_USER_ID, userID);
    }

    public static void setUsername(String username) {
        set(CommonConstants.CONTEXT_KEY_USERNAME, username);
    }

    private static String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }

    public static void remove() {
        threadLocal.remove();
    }

    private static String getObjectValue(Object obj) {
        return obj == null ? "" : obj.toString();
    }
}
